<?php
namespace app\index\controller;

class Register  {
	public function index() {
		$cteacher = model('Teacher');
		$teachers_data = $cteacher::all();
		$teachers = array();
		if ($teachers_data != null) {
			foreach ($teachers_data as $teacher_data) {
				if ($teacher_data->type == 2) {
					$teacher = array(
						'name' => $teacher_data->name,
						'tid' => $teacher_data->id
					);
					array_push($teachers, $teacher);
				}
			}
		}
        return view('/index/register', [
        	'teachers' => $teachers
        ]);
    }

    public function register() {
    	$username = input('post.username');
    	$password = input('post.password');
    	$fullname = input('post.fullname');
    	$tid = input('post.tid');
    	if ($username != null and $password != null and $fullname != null and $tid != null) {
			$cuser = model('User');
			$user_data = $cuser::where('username', $username)->find();
			// 账号不存在
			if ($user_data == null) {
				$cuser->data([
					'username' => $username,
					'password' => $password,
					'fullname' => $fullname,
					'tid' => $tid
				]);
				$cuser->save();
				return json([
	                'status' => 'success',
	                'message' => '注册成功，即将前往登录页面！',
	                'data' =>  '/index/login'
	            ]);
			}
			// 账号已注册
			else {
				return json([
	                'status' => 'error',
	                'message' => '用户名已存在！',
	                'data' =>  null
	            ]);
			}    		
    	}
    	else {
    		return json([
                'status' => 'error',
                'message' => '提交错误，请重试！',
                'data' =>  null
            ]);
    	}
    }
}